package com.zmn.oms.api.controller.third.guomei;

import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.RequestUtil;
import com.zmn.oms.third.guomei.GmqxConsts;
import com.zmn.oms.third.guomei.dto.GmqxResultDTO;
import com.zmn.oms.third.guomei.dto.GmqxSyncRequestDTO;
import com.zmn.oms.third.guomei.dto.api.GmqxSyncResult;
import com.zmn.oms.third.guomei.service.GmqxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 类描述：国美美云保清洗对外接口
 *  用于国美美云保向我方的订单推送及订单状态变更推送
 *
 * @author XieWenBing
 * @date 2019/12/03 11:00
 */
@RestController
@RequestMapping("/guomeiqingxi")
@Slf4j
public class GuomeiQingXiController {
    @Autowired
    GmqxService gmqxService;

    /**
     * 接收国美美云保推送的订单消息（创建线索，取消订单，区域验证等）
     */
    @PostMapping("/api/order")
    @ResponseBody
    public GmqxResultDTO syncOrderMsg(HttpServletRequest request) {

        // 判断功能是否打开
        if (!GmqxConsts.POWER_ON) {

            GmqxResultDTO resultDTO = new GmqxResultDTO();
            GmqxSyncResult syncResult = new GmqxSyncResult();
            syncResult.setCode(GmqxConsts.RESPONSE_CODE_SEVER_ERROR);
            syncResult.setMsg("服务接口已经关闭");

            resultDTO.setResult(syncResult);
        }

        String paramsStr = RequestUtil.getPostParameter(request);

        log.info("【{}】收到订单消息！ Body:[{}]", GmqxConsts.CHANNEL_NAME, paramsStr);

        GmqxSyncRequestDTO requestDTO = new GmqxSyncRequestDTO();
        requestDTO.setData(paramsStr);
        requestDTO.setAppId(request.getParameter("appid"));
        requestDTO.setMsgId(request.getParameter("msgId"));
        requestDTO.setMethod(request.getParameter("method"));
        requestDTO.setSign(request.getParameter("sign"));
        requestDTO.setToken(request.getParameter("token"));

        GmqxResultDTO resultDTO = null;
        try {
            resultDTO = gmqxService.handleSyncOrderMsg(requestDTO);
        } catch (OmsBaseException omsBaseException) {

            // 发生异常或错误
            resultDTO = new GmqxResultDTO();
            GmqxSyncResult syncResult = new GmqxSyncResult();
            syncResult.setCode(omsBaseException.getCode());
            syncResult.setMsg(omsBaseException.getMessage());

            resultDTO.setResult(syncResult);
        }

        return resultDTO;
    }
}
